from django.shortcuts import render, HttpResponse, redirect
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from pythonorm.main import self_login_required

@self_login_required
# @login_required()
def index(request):
    return render(request, 'index.html')
    # is_login = request.session.get('is_login',False) # 从session取出这个值说明已经登录，否则没有登录
    # if is_login:
    #     return render(request, 'index.html')
    # else:
    #     return redirect("/login")

def login(request):
    if request.method == "GET":
        return render(request, 'login.html')
    elif request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')

        """
        # 1. 对用户登录验证
        user = auth.authenticate(username=username, password=password) # 验证通过，返回一个用户名，否则为None
        print(user)
        if user:
            auth.login(request, user) # 将session写到数据库

            return redirect("/")
            # 2. 验证通过，跳转到首页
        else:
            msg = "用户名或密码错误！"
            return render(request, 'login.html',{'msg': msg})
        """
        # 从数据库里查询
        if username == "admin" and password == "123456":
            # 登录成功，将is_login设置为True
            request.session['is_login'] = True
            # 保存用户名
            request.session['username'] = username
            return redirect("/")
        else:
            msg = "用户名或密码错误！"
            return render(request, 'login.html',{'msg': msg})


def logout(request):
    auth.logout(request)
    return redirect('/login')



# 无状态协议
"""
卡片 = Cookie
卡片ID = SessionID
卡片对应的数据都是保存在服务器上
"""
